﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data.SqlClient;
using System.Data;
using BartonExtension;
using ResponseObject;
using SqlServerWrapper;
using Model;
using ZKCache;

namespace WebSrvs.NET
{
    /// <summary>
    /// ZK_BackEndService 的摘要说明
    /// </summary>
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ZK_GeneralService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
        public string catalogs()
        {
            ZKResponse response = new ZKResponse();
            string cacheIdentifier = "catalogs";
            List<Catalog> catalogs = CacheCore.standardCache.cacheWithIdentifier<List<Catalog>>(cacheIdentifier);
            if(catalogs != null)
            {
                response.userinfo = catalogs;
                return response.ToJson();
            }

            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_catalogs";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            catalogs = new List<Catalog>();
                            while(dr.Read())
                            {
                                Catalog catalog = new Catalog()
                                {
                                    ID = dr["ID"].toInt32().Value,
                                    code = dr["code"].ToString(),
                                    title = dr["title"].ToString(),
                                    title_en = dr["title_en"].ToString(),
                                    parent_code = dr["parent_code"].ToString(),
                                    layer = dr["layer"].toInt32().Value
                                };
                                catalogs.Add(catalog);
                            }
                            response.userinfo = catalogs;
                            CacheCore.standardCache.CreateCacheWithIdentifier(cacheIdentifier, catalogs);
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]
        public string brands()
        {
            ZKResponse response = new ZKResponse();
            string cacheIdentifier = "brands";
            List<Dictionary<string, object>> lstData = CacheCore.standardCache.cacheWithIdentifier<List<Dictionary<string,object>>>(cacheIdentifier);
            if(lstData != null)
            {
                response.userinfo = lstData;
                return response.ToJson();
            }
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.Text))
                {
                    cmd.CommandText = "select distinct title,level from store_info";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            lstData = new List<Dictionary<string, object>>();
                            while(dr.Read())
                            {
                                Dictionary<string, object> data = new Dictionary<string, object>();
                                data.Add("title", dr["title"]);
                                data.Add("level", dr["level"]);
                                lstData.Add(data);
                            }
                            response.userinfo = lstData;
                            CacheCore.standardCache.CreateCacheWithIdentifier(cacheIdentifier, lstData);
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
        public string malls()
        {
            ZKResponse response = new ZKResponse();
            string cacheIdentifier = "malls";
            List<Mall> malls = CacheCore.standardCache.cacheWithIdentifier<List<Mall>>(cacheIdentifier);
            if(malls != null)
            {
                response.userinfo = malls;
                return response.ToJson();
            }
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_mall";
                    try
                    {
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            malls = new List<Mall>();
                            while(dr.Read())
                            {
                                Mall mall = new Mall()
                                {
                                    ID = dr["ID"].toInt32().Value,
                                    name = dr["name"].ToString(),
                                    region = dr["region"].ToString(),
                                    street = dr["street"].ToString(),
                                    code = dr["code"].ToString(),
                                    latitude = dr["mall_lat"].toFloat().Value,
                                    longitude = dr["mall_lon"].toFloat().Value
                                };
                                malls.Add(mall);
                            }
                            response.userinfo = malls;
                            CacheCore.standardCache.CreateCacheWithIdentifier(cacheIdentifier, malls);
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string stores(StoreRetriveWay way,string retriveParameter)
        {
            ZKResponse response = new ZKResponse();
            
            string cacheIdentifier = "stores_{0}_{1}".FormatWith(Enum.GetName(typeof(StoreRetriveWay),way),retriveParameter);
            List<NewStore> stores = CacheCore.standardCache.cacheWithIdentifier<List<NewStore>>(cacheIdentifier);
            if (stores != null)
            {
                response.userinfo = stores;
                return response.ToJson();
            }

            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_shops";
                    try
                    {
                        cmd.Parameters.Add("@retriveWay", SqlDbType.Int).Value = way;
                        cmd.Parameters.Add("@parameter", SqlDbType.VarChar).Value = retriveParameter;
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            stores = new List<NewStore>();
                            
                            while(dr.Read())
                            {
                                StoreCatalog catalog = new StoreCatalog()
                                {
                                    catalog = new Catalog()
                                    {
                                        title = dr["catalog_title"].ToString(),
                                        title_en = dr["catalog_title_en"].ToString(),
                                        parent_code = dr["parent_code"].ToString(),
                                        layer = dr["layer"].toInt32().Value,
                                        code = dr["catalog_code"].ToString()
                                    },
                                    top_price = dr["top_price"].toFloat().Value,
                                    low_price = dr["low_price"].toFloat().Value,
                                    isFeatured = dr["featured"].toBoolean().Value
                                };
                                int index = stores.FindIndex(s =>
                                {
                                    return s.ID == dr["ID"].toInt32().Value;
                                });
                                if (index != -1)
                                {
                                    stores[index].catalogs.Add(catalog);
                                }
                                else
                                {
                                    NewStore store = new NewStore() { catalogs = new List<StoreCatalog>() };
                                    store.ID = dr["ID"].toInt32().Value;
                                    store.title = dr["title"].ToString();
                                    store.type = (StoreType)dr["type"].toInt32().Value;
                                    store.frequency = dr["frequency"].toFloat().Value;
                                    store.duration = dr["duration"].toFloat().Value;
                                    store.level = dr["level"].toFloat().Value;
                                    store.live_time = dr["live_time"].ToString();
                                    store.tel = dr["tel"].ToString();
                                    store.desc = dr["desc"].ToString();
                                    Mall mall = new Mall();
                                    mall.code = dr["mall_code"].ToString();
                                    mall.name = dr["name"].ToString();
                                    mall.region = dr["region"].ToString();
                                    mall.street = dr["street"].ToString();
                                    mall.latitude = dr["m_lat"].toFloat().Value;
                                    mall.longitude = dr["m_lon"].toFloat().Value;
                                    store.mall = mall;
                                    store.in_mall_location = dr["in_mall_location"].ToString();
                                    store.lat = dr["s_lat"].toFloat().Value;
                                    store.lon = dr["s_lon"].toFloat().Value;
                                    store.catalogs.Add(catalog);
                                    stores.Add(store);
                                }
                            }
                            response.isProcessSuccess = true;
                            response.errCode = ErrorCodes.CODE_ERR_NO_ERR;
                            response.userinfo = stores;
                            CacheCore.standardCache.CreateCacheWithIdentifier(cacheIdentifier, stores);
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
        
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string activities()
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_activities";
                    try
                    {
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            List<Activity> activities = new List<Activity>();
                            while (dr.Read())
                            {
                                Activity act = new Activity();
                                act.ID = dr["ID"].toInt32().Value;
                                act.store_id = dr["store_id"].toInt32().Value;
                                act.catalog_ids = dr["catalog_ids"].ToString();
                                act.sale_desc = dr["sale_desc"].ToString();
                                act.sale_rate = dr["sale_rate"].toFloat().Value;
                                act.status = (ActivityStatus)dr["status"].toInt32().Value;
                                act.discount_rate = dr["discount_rate"].toFloat().Value;
                                act.time_from = dr["time_from"].ToString();
                                act.time_to = dr["time_to"].ToString();
                                act.images = dr["images"].ToString();
                                act.on_show_type = (ActivityShowType)dr["on_show_type"].toInt32().Value;
                                activities.Add(act);
                            }
                            response.userinfo = activities;
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string BrandInStoreExists(int store_id, int brand_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_brand";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@brand_id", SqlDbType.Int).Value = brand_id;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_LOCATION_EXIST;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_LOCATION_EXIST;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CatalogInStoreExists(int store_id, int catalog_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_brand";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@catalog_id", SqlDbType.Int).Value = catalog_id;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_LOCATION_EXIST;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_LOCATION_EXIST;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string catalogExists(string code)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_catalog_existence_check";
                    cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_CATALOG_CODE_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_CATALOG_CODE_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string brandExists(string code)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_brand_existence_check";
                    cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = code;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BRAND_CODE_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BRAND_CODE_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string get_user_shares(int page_size,int page_idx)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using(SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using(SqlCommand cmd = SqlCommandManager.Create(conn,CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_get_user_shares";
                    cmd.Parameters.Add("@page_size", SqlDbType.Int).Value = page_size;
                    cmd.Parameters.Add("@page_idx", SqlDbType.Int).Value = page_idx;
                    try
                    {
                        using(SqlDataReader dr = cmd.ExecuteReader())
                        {
                            List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
                            while(dr.Read())
                            {
                                Dictionary<string, object> data = new Dictionary<string, object>();
                                for(int i=0;i<dr.FieldCount;i++)
                                {
                                    data.Add(dr.GetName(i), dr[i]);
                                }
                                result.Add(data);
                            }
                            response.userinfo = result;
                        }
                    }
                    catch(Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errMsg = ex.Message;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                    }
                }
            }
            return response.ToJson();
        }
    }
}
